<template>
  <div class="babylon-exhibition-container">
    <div class="exhibition-header">
      <!-- <button class="back-button" @click="goBack">← 退出展览</button> -->
      <h1>3D书法艺术展览馆</h1>
      <div class="spacer"></div>
    </div>

    <div ref="babylonContainer" class="babylon-container"></div>

    <div class="loading-indicator" v-if="loading">
      <div class="spinner"></div>
      <p>正在构建3D展览空间...</p>
    </div>

    <div class="exhibition-controls">
      <div class="control-group">
        <button @click="toggleAutoRotation" :class="{ active: isAutoRotating }" title="自动旋转">
          {{ isAutoRotating ? '停止' : '自动旋转' }}
        </button>
        <button @click="birdView" title="鸟瞰视角">👁</button>
        <button @click="resetView" title="重置视角">⌀</button>
        <button @click="toggleWireframe" :class="{ active: wireframeMode }" title="线框模式">
          线框
        </button>
      </div>

      <div class="control-group">
        <button @click="previousArtwork" title="上一个作品">←</button>
        <button @click="nextArtwork" title="下一个作品">→</button>
      </div>
    </div>

    <!-- 作品信息面板 -->
    <div class="artwork-info-panel" v-if="selectedArtwork">
      <div class="info-header">
        <h2>{{ selectedArtwork.title }}</h2>
        <button @click="closeInfoPanel" class="close-btn">×</button>
      </div>
      <div class="info-content">
        <p><strong>作者：</strong>{{ selectedArtwork.artist }}</p>
        <p><strong>朝代：</strong>{{ selectedArtwork.dynasty }}</p>
        <p><strong>书体：</strong>{{ selectedArtwork.style }}</p>
        <p><strong>简介：</strong>{{ selectedArtwork.description }}</p>
        <p><strong>创作背景：</strong>{{ selectedArtwork.background }}</p>
        <p><strong>艺术特色：</strong>{{ selectedArtwork.features }}</p>
      </div>
    </div>

    <!-- 操作提示 -->
    <div class="touch-hint" v-if="showHint">
      <p>💡 3D展览馆操作指南：</p>
      <p>• 鼠标左键拖动：旋转视角</p>
      <p>• 鼠标右键拖动：平移视角</p>
      <p>• 鼠标滚轮：缩放</p>
      <p>• 点击作品：查看详情</p>
      <p>• 自动旋转：开启后作品自动旋转展示</p>
      <button @click="hideHint">知道了</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// Babylon.js imports
import * as BABYLON from '@babylonjs/core'

// API导入
import { artworkApi } from '@/api'

// Router
const route = useRoute()
const router = useRouter()

// Refs
const babylonContainer = ref(null)

// State
let engine = null
let scene = null
let camera = null
let canvas = null

let loading = ref(true)
let showHint = ref(true)
let isAutoRotating = ref(false)
let wireframeMode = ref(false)
let selectedArtwork = ref(null)

// Animation variables
let rotationAnimation = null
let currentArtworkIndex = 0

// 作品数据
const artworks = ref([])

// 当前作品
const currentArtwork = computed(() => {
  return artworks.value[currentArtworkIndex]
})

// 获取作品数据
const fetchArtworks = async () => {
  try {
    const response = await artworkApi.getArtworks()
    // 为每个作品添加位置信息
    artworks.value = response.data.map((artwork, index) => {
      // 计算位置，将作品均匀分布在圆形中
      const angle = (index / response.data.length) * Math.PI * 2
      const radius = 8
      return {
        ...artwork,
        position: {
          x: Math.cos(angle) * radius,
          y: 0,
          z: Math.sin(angle) * radius
        }
      }
    })
  } catch (error) {
    console.error('获取作品数据失败:', error)
    // 如果API调用失败，使用模拟数据
    useMockData()
  }
}

// 使用模拟数据（备用方案）
const useMockData = () => {
  artworks.value = [
    {
      id: 1,
      title: '兰亭序',
      artist: '王羲之',
      dynasty: '东晋',
      style: '行书',
      category: 'ancient',
      description: '被誉为"天下第一行书"，是王羲之在兰亭雅集时所作，书法飘逸秀美，气韵生动。',
      background: '东晋永和九年（353年），王羲之与谢安、孙绰等四十一位军政高官在山阴兰亭会聚，饮酒赋诗，王羲之为此诗集作序。',
      features: '笔法飘逸秀美，气韵生动，章法自然，体现了王羲之书法艺术的最高成就。此作品在3D建模中展现了笔画的立体感和墨色的层次变化。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: { x: 0, y: 0, z: 0 }
    },
    {
      id: 2,
      title: '祭侄文稿',
      artist: '颜真卿',
      dynasty: '唐代',
      style: '行书',
      category: 'ancient',
      description: '颜真卿为祭奠侄子颜季明所作，书法雄浑悲壮，被誉为"天下第二行书"。',
      background: '安史之乱时，颜真卿的侄子颜季明在抵抗叛军时被害，颜真卿悲愤交加写下此文。',
      features: '笔法雄浑，情感真挚，线条粗细变化丰富，体现了颜体行书的独特风格。3D建模突出了笔画的力度感和情感表达。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: { x: 5, y: 0, z: 0 }
    },
    {
      id: 3,
      title: '黄州寒食诗帖',
      artist: '苏轼',
      dynasty: '宋代',
      style: '行书',
      category: 'ancient',
      description: '苏轼被贬黄州时所作，书法自然流畅，情感真挚，体现了文人书法的独特韵味。',
      background: '苏轼被贬黄州第三年寒食节时所作，表达了对人生际遇的感慨。',
      features: '笔法自然，结构疏密有致，体现了文人书法的独特韵味。3D建模展现了字体的自然流动感。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: { x: -5, y: 0, z: 0 }
    },
    {
      id: 4,
      title: '自叙帖',
      artist: '怀素',
      dynasty: '唐代',
      style: '草书',
      category: 'ancient',
      description: '怀素的代表作之一，笔法狂放不羁，线条流畅如行云流水，展现了草书的极致之美。',
      background: '怀素在长安与文人雅士交往时所作，记录了自己学习草书的经历。',
      features: '笔法狂放，线条流畅如行云流水，展现了草书的极致之美。3D建模突出了草书的动感和韵律。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: { x: 0, y: 0, z: 5 }
    },
    {
      id: 5,
      title: '急就章',
      artist: '宋克',
      dynasty: '明代',
      style: '章草',
      category: 'ancient',
      description: '明代书法家宋克的章草代表作，笔法古朴，结构严谨，体现了章草的独特韵味。',
      background: '明代书法家宋克的章草代表作，体现了章草的独特韵味。',
      features: '笔法古朴，结构严谨，体现了章草的独特韵味。3D建模还原了古朴的笔法特征。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: { x: 0, y: 0, z: -5 }
    },
    {
      id: 6,
      title: '毛泽东诗词',
      artist: '毛泽东',
      dynasty: '现代',
      style: '草书',
      category: 'modern',
      description: '毛泽东的书法作品，气势磅礴，笔力雄健，体现了革命家的豪迈气概。',
      background: '毛泽东的书法作品，体现了革命家的豪迈气概。',
      features: '气势磅礴，笔力雄健，体现了革命家的豪迈气概。3D建模展现了豪迈的气势。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: { x: 3, y: 0, z: 3 }
    }
  ]
}

// 返回上一页
const goBack = () => {
  router.push('/exhibition')
}

// 隐藏提示
const hideHint = () => {
  showHint.value = false
}

// 关闭信息面板
const closeInfoPanel = () => {
  selectedArtwork.value = null
}

// 初始化Babylon.js
const initBabylon = async () => {
  try {
    if (!babylonContainer.value) {
      console.error('Babylon容器未找到')
      return
    }

    // 创建canvas元素
    canvas = document.createElement('canvas')
    canvas.style.width = '100%'
    canvas.style.height = '100%'
    canvas.style.outline = 'none'
    babylonContainer.value.appendChild(canvas)

    // 创建引擎
    engine = new BABYLON.Engine(canvas, true, {
      preserveDrawingBuffer: true,
      stencil: true,
      disableWebGL2Support: false
    })

    // 创建场景
    scene = new BABYLON.Scene(engine)
    scene.clearColor = new BABYLON.Color4(0.1, 0.1, 0.1, 1)

    // 创建相机
    camera = new BABYLON.ArcRotateCamera(
      'camera',
      -Math.PI / 2,
      Math.PI / 2.5,
      15,
      new BABYLON.Vector3(0, 0, 0),
      scene
    )
    camera.attachControl(canvas, true)
    camera.lowerRadiusLimit = 5
    camera.upperRadiusLimit = 30

    // 添加光源
    const light1 = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0, 1, 0), scene)
    light1.intensity = 0.7

    const light2 = new BABYLON.DirectionalLight('light2', new BABYLON.Vector3(-1, -1, -1), scene)
    light2.position = new BABYLON.Vector3(20, 40, 20)
    light2.intensity = 0.7

    // 创建展览环境
    createExhibitionEnvironment()

    // 创建作品展示
    await createArtworkDisplays()

    // 添加点击检测
    addClickDetection()

    // 开始渲染循环
    engine.runRenderLoop(() => {
      scene.render()
    })

    // 监听窗口大小变化
    window.addEventListener('resize', onWindowResize)

    // 隐藏加载指示器
    loading.value = false
  } catch (error) {
    console.error('初始化Babylon.js时发生错误:', error)
    loading.value = false
  }
}

// 创建展览环境
const createExhibitionEnvironment = () => {
  // 创建地面
  const ground = BABYLON.MeshBuilder.CreateGround('ground', { width: 30, height: 30 }, scene)
  const groundMaterial = new BABYLON.StandardMaterial('groundMaterial', scene)
  groundMaterial.diffuseColor = new BABYLON.Color3(0.2, 0.2, 0.2)
  groundMaterial.specularColor = new BABYLON.Color3(0, 0, 0)
  ground.material = groundMaterial

  // 添加网格线
  const grid = BABYLON.Mesh.CreateGround('grid', 30, 30, 30, scene, true)
  const gridMaterial = new BABYLON.StandardMaterial('gridMaterial', scene)
  gridMaterial.wireframe = true
  gridMaterial.alpha = 0.2
  grid.material = gridMaterial

  // 创建背景球体
  const sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 100 }, scene)
  const sphereMaterial = new BABYLON.StandardMaterial('sphereMaterial', scene)
  sphereMaterial.diffuseColor = new BABYLON.Color3(0.05, 0.05, 0.1)
  sphereMaterial.specularColor = new BABYLON.Color3(0, 0, 0)
  sphereMaterial.backFaceCulling = false
  sphere.material = sphereMaterial
  sphere.invertNormal = true

  // 添加装饰性柱子
  for (let i = -2; i <= 2; i++) {
    if (i === 0) continue // 跳过中心位置
    
    const pillar = BABYLON.MeshBuilder.CreateCylinder('pillar_' + i, {
      height: 10,
      diameter: 0.5
    }, scene)
    
    pillar.position.x = i * 6
    pillar.position.y = 5
    pillar.position.z = -14.5
    
    const pillarMaterial = new BABYLON.StandardMaterial('pillarMat_' + i, scene)
    pillarMaterial.diffuseColor = new BABYLON.Color3(0.4, 0.4, 0.4)
    pillarMaterial.specularColor = new BABYLON.Color3(0.1, 0.1, 0.1)
    pillar.material = pillarMaterial
  }
}

// 创建作品展示
const createArtworkDisplays = async () => {
  artworks.value.forEach((artwork, index) => {
    // 创建展示台
    const displayBase = BABYLON.MeshBuilder.CreateCylinder('base_' + artwork.id, {
      height: 0.3,
      diameter: 2.5
    }, scene)
    
    displayBase.position.x = artwork.position.x
    displayBase.position.y = 0.15
    displayBase.position.z = artwork.position.z
    
    const baseMaterial = new BABYLON.StandardMaterial('baseMat_' + artwork.id, scene)
    baseMaterial.diffuseColor = new BABYLON.Color3(0.4, 0.4, 0.4)
    baseMaterial.specularColor = new BABYLON.Color3(0.1, 0.1, 0.1)
    displayBase.material = baseMaterial

    // 创建展示板（用于显示图片）
    const displayBoard = BABYLON.MeshBuilder.CreatePlane('board_' + artwork.id, { width: 1.8, height: 1.8 }, scene)
    
    displayBoard.position.x = artwork.position.x
    displayBoard.position.y = 1.5
    displayBoard.position.z = artwork.position.z + 0.06
    
    // 确保展示板面向观众
    displayBoard.rotation.x = 0
    displayBoard.rotation.y = 0
    displayBoard.rotation.z = 0
    
    const boardMaterial = new BABYLON.StandardMaterial('boardMat_' + artwork.id, scene)
    boardMaterial.diffuseColor = new BABYLON.Color3(0.95, 0.9, 0.8) // 米黄色，类似宣纸
    
    // 加载作品图片作为纹理
    const texture = new BABYLON.Texture(artwork.image, scene, false, true, BABYLON.Texture.NEAREST_SAMPLINGMODE)
    
    // 添加加载成功回调
    if (texture.onLoadObservable) {
      texture.onLoadObservable.add(() => {
        console.log('图片加载成功:', artwork.title, artwork.image)
        boardMaterial.diffuseTexture = texture
        // 设置纹理属性
        if (texture) {
          texture.hasAlpha = false
          texture.uScale = 1
          texture.vScale = 1
        }
      })
    }
    
    // 添加加载失败回调
    if (texture.onErrorObservable) {
      texture.onErrorObservable.add((error) => {
        console.error('图片加载失败:', artwork.title, artwork.image, error)
        // 加载失败时保持背景色
      })
    }
    
    displayBoard.material = boardMaterial

    // 创建作品标题文本（放在展示板上方）
    const text = artwork.title
    const textBlock = new BABYLON.DynamicTexture('text_' + artwork.id, { width: 256, height: 128 }, scene)
    const font = "bold 24px Arial"
    textBlock.drawText(text, null, 64, font, "black", "transparent", true)
    
    const textMaterial = new BABYLON.StandardMaterial('textMat_' + artwork.id, scene)
    textMaterial.diffuseTexture = textBlock
    textMaterial.specularColor = new BABYLON.Color3(0, 0, 0)
    
    const textPlane = BABYLON.MeshBuilder.CreatePlane('textPlane_' + artwork.id, { width: 1.8, height: 0.5 }, scene)
    textPlane.position.x = artwork.position.x
    textPlane.position.y = 2.8
    textPlane.position.z = artwork.position.z + 0.07
    textPlane.material = textMaterial

    // 保存引用以便交互
    artwork.displayObject = displayBoard
    artwork.textObject = textPlane
  })
}

// 添加点击检测
const addClickDetection = () => {
  canvas.addEventListener('click', (evt) => {
    // 创建射线投射器
    const pickResult = scene.pick(scene.pointerX, scene.pointerY)
    
    if (pickResult.hit) {
      // 检查是否点击了作品展示板或标题
      for (const artwork of artworks.value) {
        // 检查是否点击了展示板
        if (artwork.displayObject && pickResult.pickedMesh.alphaIndex === artwork.displayObject.alphaIndex) {
          selectedArtwork.value = artwork
          break
        }
        
        // 检查是否点击了标题
        if (artwork.textObject && pickResult.pickedMesh === artwork.textObject) {
          selectedArtwork.value = artwork
          break
        }
      }
    }
  })
}

// 切换自动旋转
const toggleAutoRotation = () => {
  isAutoRotating.value = !isAutoRotating.value
  
  if (isAutoRotating.value) {
    // 开始旋转动画
    rotationAnimation = scene.onBeforeRenderObservable.add(() => {
      scene.meshes.forEach(mesh => {
        if (mesh.name.startsWith('board_')) {
          mesh.rotation.y += 0.005
        }
      })
    })
  } else {
    // 停止旋转动画
    if (rotationAnimation) {
      scene.onBeforeRenderObservable.remove(rotationAnimation)
      rotationAnimation = null
    }
  }
}

// 鸟瞰视角
const birdView = () => {
  if (camera) {
    camera.alpha = -Math.PI / 2
    camera.beta = 0.1
    camera.radius = 20
  }
}

// 重置视角
const resetView = () => {
  if (camera) {
    camera.alpha = -Math.PI / 2
    camera.beta = Math.PI / 2.5
    camera.radius = 15
  }
}

// 切换线框模式
const toggleWireframe = () => {
  wireframeMode.value = !wireframeMode.value
  
  scene.meshes.forEach(mesh => {
    if (mesh.material) {
      mesh.material.wireframe = wireframeMode.value
    }
  })
}

// 上一个作品
const previousArtwork = () => {
  console.log('点击上一个作品按钮，当前索引:', currentArtworkIndex)
  currentArtworkIndex = (currentArtworkIndex - 1 + artworks.value.length) % artworks.value.length
  console.log('新索引:', currentArtworkIndex)
  focusOnCurrentArtwork()
}

// 下一个作品
const nextArtwork = () => {
  console.log('点击下一个作品按钮，当前索引:', currentArtworkIndex)
  currentArtworkIndex = (currentArtworkIndex + 1) % artworks.value.length
  console.log('新索引:', currentArtworkIndex)
  focusOnCurrentArtwork()
}

// 聚焦当前作品
const focusOnCurrentArtwork = () => {
  const artwork = currentArtwork.value
  console.log('聚焦到作品:', artwork) // 添加调试信息
  
  if (camera && artwork) {
    // 直接设置相机目标到作品位置
    const target = new BABYLON.Vector3(artwork.position.x, 1.5, artwork.position.z)
    camera.setTarget(target)
    
    // 调整相机半径和角度以获得更好的视角
    camera.radius = 5
    camera.beta = Math.PI / 3 // 60度俯角
    
    console.log('相机已聚焦到作品:', artwork.title)
  } else {
    console.log('无法聚焦到作品，camera或artwork为空')
  }
}

// 窗口大小调整
const onWindowResize = () => {
  if (engine) {
    engine.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  fetchArtworks().then(() => {
    initBabylon()
  })
})

// 组件卸载时清理
onUnmounted(() => {
  // 停止渲染循环
  if (engine) {
    engine.stopRenderLoop()
  }
  
  // 销毁场景
  if (scene) {
    scene.dispose()
  }
  
  // 销毁引擎
  if (engine) {
    engine.dispose()
  }
  
  // 移除事件监听器
  window.removeEventListener('resize', onWindowResize)
})
</script>

<style scoped>
.babylon-exhibition-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.exhibition-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  z-index: 10;
}

.exhibition-header h1 {
  margin: 0;
  font-size: 1.5rem;
  color: #fff;
}

.back-button {
  background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.back-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.spacer {
  width: 60px;
}

.babylon-container {
  flex: 1;
  width: 100%;
  outline: none;
}

.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
  z-index: 5;
}

.spinner {
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top: 4px solid #fff;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.exhibition-controls {
  position: absolute;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 1rem;
  z-index: 10;
}

.control-group {
  display: flex;
  gap: 0.5rem;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 0.5rem;
  border-radius: 8px;
}

.control-group button {
  padding: 0.5rem 1rem;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.control-group button:hover {
  background-color: #667eea;
  transform: translateY(-2px);
}

.control-group button.active {
  background-color: #667eea;
  box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
}

.artwork-info-panel {
  position: absolute;
  top: 0;
  right: 0;
  width: 350px;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: -5px 0 15px rgba(0, 0, 0, 0.3);
  z-index: 15;
  display: flex;
  flex-direction: column;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #34495e;
  color: white;
}

.info-header h2 {
  margin: 0;
  font-size: 1.3rem;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
}

.info-content {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
}

.info-content p {
  margin: 0.8rem 0;
  line-height: 1.5;
}

.touch-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.9);
  color: white;
  padding: 2rem;
  border-radius: 10px;
  text-align: center;
  z-index: 20;
  max-width: 90%;
  width: 400px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.touch-hint p {
  margin: 0.8rem 0;
  text-align: left;
  line-height: 1.5;
}

.touch-hint button {
  background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 1rem;
  transition: all 0.3s ease;
}

.touch-hint button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}

@media (max-width: 768px) {
  .exhibition-header {
    padding: 0.5rem 1rem;
  }

  .exhibition-header h1 {
    font-size: 1.2rem;
  }

  .touch-hint {
    width: 90%;
    padding: 1.5rem;
  }

  .exhibition-controls {
    bottom: 1rem;
    flex-wrap: wrap;
    justify-content: center;
    width: 90%;
    left: 5%;
    transform: none;
  }

  .artwork-info-panel {
    width: 100%;
  }
}
</style>